package com.uam.core.lk.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.uam.core.lk.utils.constant.Constants;

/**
 * @Description  获得真实IP
 * @Version 1.0
 * @Author 祝展
 * @Date 2019/10/23 15:34
 **/
public class IpUtils {

    public static final String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader(Constants.X_FORWARDED_FOR);
        if (StringUtils.isEmpty(ip) || Constants.UNKNOWN.equalsIgnoreCase(ip)) {
            if (StringUtils.isEmpty(ip) || Constants.UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader(Constants.PROXY_CLIENT_IP);
            }
            if (StringUtils.isEmpty(ip) || Constants.UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader(Constants.WL_PROXY_CLIENT_IP);
            }
            if (StringUtils.isEmpty(ip) || Constants.UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader(Constants.HTTP_CLIENT_IP);
            }
            if (StringUtils.isEmpty(ip) || Constants.UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader(Constants.HTTP_X_FORWARDED_FOR);
            }
            if (StringUtils.isEmpty(ip) || Constants.UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = ips[index];
                if (!(Constants.UNKNOWN.equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }

    private IpUtils() {
    }
}
